#!/bin/bash

SWNAME=clash
SWVER=2.2.2

# 注意安装顺序，后装者依赖前装者
DEB_PATH1=./downloads/${SWNAME}-${SWVER}.deb

DIR_DESKTOP_FILES=/usr/share/applications
DSK_FILE=${SWNAME}.desktop
DSK_PATH=${DIR_DESKTOP_FILES}/${DSK_FILE}

action=$1
if [ "$action" == "" ]; then action=安装; fi

. ./scripts/common.sh

function sw_download() {
	case "${CURRENT_VM_ARCH}" in
		"arm64")
			swUrl="${GITHUB_PROXY_HTTP}https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v2.2.2/Clash.Verge_2.2.2_arm64.deb"
			download_file2 "${DEB_PATH1}" "${swUrl}"
			exit_if_fail $? "下载失败，网址：${swUrl}"
		;;
		*) exit_unsupport ;;
	esac
}

function sw_install() {

	# apt-get install -y libasound2t64
	# exit_if_fail $? "依赖库安装失败"

	install_deb ${DEB_PATH1} ${DEB_PATH2} ${DEB_PATH3}
	install_deb ${DEB_PATH1}
	exit_if_fail $? "安装失败，软件包：${DEB_PATH1}"

}

function sw_create_desktop_file() {
	echo "正在生成启动脚本"
	tmpfile=/usr/bin/${SWNAME}
	cat <<- EOF > ${tmpfile}
		#!/bin/bash
		port=\`cat ~/.local/share/io.github.clash-verge-rev.clash-verge-rev/config.yaml 2>/dev/null|grep mixed-port|awk '{print \$2;}'\`
		if [ "\$port" == "" ]; then
			gxmessage -center -title "错误" "clash端口获取失败"
			exit 1
		fi
		ps ax|grep mihomo|grep -v grep
		if [ \$? -ne 0 ]; then
			gxmessage -center -title "错误" "clash未启动, 请先启动"
			exit 1
		fi
		export  http_proxy=http://127.0.0.1:\$port
		export https_proxy=http://127.0.0.1:\$port
		exec \$@
	EOF
	chmod 755 ${tmpfile}

	echo "正在处理chrome浏览器图标"
	cp -f ${ZZ_USER_HOME}/Desktop/chrome.desktop   ${ZZ_USER_HOME}/Desktop/proxied_chrome.desktop
	sed -i "s|Exec=|Exec=clash |g"                 ${ZZ_USER_HOME}/Desktop/proxied_chrome.desktop
	sed -i "s|Name=Chrome|Name=使用代理|g"         ${ZZ_USER_HOME}/Desktop/proxied_chrome.desktop

	(cd /usr/share/applications && mv 'Clash Verge.desktop'  ${DSK_FILE})
	exit_if_fail $? "启动图标处理失败"

	tmpfile=${DSK_PATH}
	cp2desktop ${tmpfile}

	gxmessage -title "提示"     $'\n安装完成\n\n'  -center
}

if [ "${action}" == "卸载" ]; then
	# echo "暂不支持卸载"
	# exit 1

	pkgname2rm=clash-verge
	echo "正在 dpkg --remove --force-remove-reinstreq ${pkgname2rm}"
	dpkg --remove --force-remove-reinstreq ${pkgname2rm}
	exit_if_fail $? "force-remove-reinstreq 失败"

	echo "正在 apt-get purge ${pkgname2rm} -y"
	apt-get purge ${pkgname2rm} -y

	rm -rf ${app_dir} ${DIR_DESKTOP_FILES}/${SWNAME}.desktop
	rm2desktop ${SWNAME}.desktop
else
	sw_download
	sw_install
	sw_create_desktop_file
fi

